package com.start.workflow.core.load;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.start.common.entity.StartBaseUser;
import com.start.common.user.StartUserInfoLoadService;
import com.start.workflow.common.model.StartActBusinessModel;
import com.start.workflow.common.model.StartActConfigModel;
import com.start.workflow.common.std.IStartActCandidateLoad;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class StartActCustomCandidateLoad implements IStartActCandidateLoad {
    public static final String CUSTOM_AUTH_CANDIDATE = "custom_auth_candidate";

    /**
     * 类别
     *
     * @return
     */
    @Override
    public String categoryKey() {
        return "system_category";
    }

    /**
     * 类别名称
     *
     * @return
     */
    @Override
    public String categoryName() {
        return "系统";
    }

    /**
     * 候选人类型
     *
     * @return
     */
    @Override
    public String actCandidateType() {
        return CUSTOM_AUTH_CANDIDATE;
    }

    /**
     * 候选者类型名称
     *
     * @return
     */
    @Override
    public String actCandidateLabel() {
        return "提交选择用户";
    }

    @Override
    public String actCandidateDesc() {
        return "提交时自行选择审批人";
    }

    @Override
    public boolean isGlobal() {
        return IStartActCandidateLoad.super.isGlobal();
    }

    /**
     * 加载
     *
     * @param curActBus
     * @param config
     * @return
     */
    @Override
    public List<StartBaseUser> load(StartActBusinessModel curActBus, StartActConfigModel config) {
        List<StartBaseUser> customActAuthUsers = JSONArray.parseArray(config.getConfVal(), StartBaseUser.class);
        if (customActAuthUsers.isEmpty()) return null;
        Map<String, List<String>> listMap = customActAuthUsers.stream().filter(e -> StringUtils.isNotBlank(e.getStartUserType()) && StringUtils.isNotBlank(e.getId())).collect(Collectors.groupingBy(StartBaseUser::getStartUserType, Collectors.mapping(StartBaseUser::getId, Collectors.toList())));
        List<StartBaseUser> result = new ArrayList<>();
        for (String key : listMap.keySet()) {
            List<StartBaseUser> users = StartUserInfoLoadService.getInstance().getByUserIds(key, listMap.get(key));
            if (users == null || users.isEmpty()) {
                continue;
            }
            result.addAll(users);
        }
        return result;
    }

}
